//
//  StarLoadingViewController.m
//  17LoanTemplate
//
//  Created by gynjobs on 2017/8/23.
//  Copyright © 2017年 cangming. All rights reserved.
//

#import "StarLoadingViewController.h"
#import "NotificationManager.h"
#import <CommonCrypto/CommonDigest.h>
#import "HDJSInjectAction.h"
#import "ChangeRootViewTool.h"
#import "HDDeviceInfoUploadHelper.h"
#import "RegiestDeviceNumber.h"
#import "NetRequestModle.h"
@interface StarLoadingViewController ()

@end

@implementation StarLoadingViewController
int timeoutcount = 0;

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //    [TalkingData trackPageBegin:@"LoadingViewController"];
    //    [TalkingData trackEvent:@"进入loading页面" label:[APP_NO stringValue]];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //    [TalkingData trackPageEnd:@"LoadingViewController"];
    
}
- (void)LoadingLaunchView{
    UIImageView *bg = [UIImageView new];
    bg.frame = self.view.frame;
    bg.image = [UIImage imageNamed:@"sesameLoan"];
    [self.view addSubview:bg];
    UIActivityIndicatorView *loading = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    loading.center = CGPointMake(kWidth/2.0, kHeight-150);
    [loading startAnimating];
    [self.view addSubview:loading];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNeedsStatusBarAppearanceUpdate];
    
    [self LoadingLaunchView];
    if ([RegiestDeviceNumber isAlreadRegiesteredDevice]) {
        [self checkActive];
    }
    else {
        [self registerDevice];
    }
    if (IOS9_OR_LATER) {
        [self preferredStatusBarStyle];
    }else{
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    }
    
    
    // Do any additional setup after loading the view.
}
- (UIStatusBarStyle)preferredStatusBarStyle{
    
    return UIStatusBarStyleLightContent;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)registerDevice{
    [EncryptAction removeAuthKey];
    [RegiestDeviceNumber regiesterDevice:^(NSError *error) {
        if (!error) {
            [self checkActive];
        }
        else {
            if (timeoutcount <= 12) {
                timeoutcount++;
                [self performSelector:@selector(registerDevice) withObject:nil afterDelay:1];
                return;
            }
            [CustomAlertView alertShowTitle:@"初始化数据失败" message:@"请检查网络然后重试" cancelButtonTitle:@"取消" otherButtonTitles:@"重试" block:^(NSInteger buttonIndex) {
                if (buttonIndex==1) {
                    [self registerDevice];
                }
            }];
        }
        
    }];
}

- (void)checkActive{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSString *strKey = [NSString stringWithFormat:@"activeStatus_%@",app_Version];
    if ([[[NSUserDefaults standardUserDefaults] valueForKey:strKey] boolValue]) {
        [self createHomeController];
        
        [self checkNewVersion];
        return;
    }
    if ([[[NSUserDefaults standardUserDefaults] valueForKey:strKey] boolValue]) {
        [self createHomeController];
        
        [self checkNewVersion];
        return;
    }
    [NetRequestModle getTheAppCheckStatusForStar:^(NSError *error) {
        if (!error) {
            BOOL status = [[[NSUserDefaults standardUserDefaults] valueForKey:strKey] boolValue];
            if (status) {
                [self createHomeController];
                
                [self checkNewVersion];
            }
            else {
                
                switch ([TYPE_NO integerValue]) {
                    case 10:{
                        [self createHomeController];
                        [[NotificationManager getInstance] startListen];
                    }
                        break;
                    default:{
                        [self performSelector:@selector(goBeforCheckView) withObject:nil afterDelay:2];
                    }
                        break;
                }
            }
        }
        else {
            if (error.code==113||error.code==114) {
                [self registerDevice];
                return;
            }
            if (timeoutcount <= 14) {
                timeoutcount++;
                [self performSelector:@selector(checkActive) withObject:nil afterDelay:3];
                return;
            }
            NSInteger tagIndex = 9528;
            if (error.code==113||error.code==114) {
                tagIndex = 9527;
            }
            [CustomAlertView alertShowTitle:@"初始化数据失败-1003" message:@"请检查网络然后重试" cancelButtonTitle:@"取消" otherButtonTitles:@"重试" block:^(NSInteger buttonIndex) {
                if (buttonIndex==1) {
                    if (tagIndex == 9527) {
                        [self registerDevice];
                    }
                    else {
                        [self checkActive];
                    }
                }
            }];
        }
    }];
}

- (void)getH5URL{
    //    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    //    [[ClientApi getInstance] getLoanListH5Address:^(id  _Nullable responseObject, NSError * _Nullable error) {
    //        if (!error) {
    //            delegate.h5data = responseObject[@"items"];
    //        }
    //    }];
}

- (void)getMainTabData{
    //    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    //    [[ClientApi getInstance] getTest:^(id  _Nullable responseObject, NSError * _Nullable error) {
    //        NSLog(@"zzz");
    //    }];
}

- (void)checkNewVersion{
    NSString *version = [[NSUserDefaults standardUserDefaults] valueForKey:@"version"];
    if (!version) {
        version = @"1";
    }
    [[ClientApi getInstance] checkAppVersionStatus:@{@"app_v":version} callback:^(id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            if ([responseObject[@"update"] boolValue]) {
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    NSString *url = responseObject[@"url"];
                    NSURLResponse *repsonse = nil;
                    NSData *data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]] returningResponse:&repsonse error:nil];
                    if (![[self md5:data] isEqualToString:responseObject[@"md5"]]) {
                        return;
                    }
                    
                    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                    NSString *docDir = [paths objectAtIndex:0];
                    //        NSFileManager *fileManager = [NSFileManager defaultManager];
                    
                    NSString *jsBundleFile = [docDir stringByAppendingString:@"/demo"];
                    BOOL dd = [data writeToFile:jsBundleFile atomically:YES];
                    if (dd ){
                        [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%@",responseObject[@"app_v"]] forKey:@"version"];
                    }
                });
                
            }
        }
    }];
}

- (NSString*)md5:(NSData *)data
{
    unsigned char result[16];
    CC_MD5( data.bytes, (CC_LONG)data.length, result ); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}



/*
 考虑3种情况：
 1.正常情况3秒返回页面数据
 2.超时，没有缓存数据
 3.超时，有缓存数据
 */

- (void)createHomeController{
    
    
    [[NotificationManager getInstance] getLoanBaoxianStatus];
    [[NotificationManager getInstance] getLoanListTipStatus];
    
    
    [[HDJSInjectAction shareInstance] getJS];
    [HDDeviceInfoUploadHelper uploadCurrentDeviceInfo];
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(20 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [HDDeviceInfoUploadHelper uploadCurrentGPSLocation];
    });
    [[ClientApi getInstance] getTest:^(id  _Nullable responseObject, NSError * _Nullable error) {
        
        NSDictionary *dictTabData = [[NSUserDefaults standardUserDefaults] valueForKey:@"tabData"];
        if (!error) {
            NSArray *temp = responseObject[@"items"];
            NSArray *array = [temp sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                NSNumber *number1 = obj1[@"id"];
                NSNumber *number2 = obj2[@"id"];
                NSComparisonResult result = [number1 compare:number2];
                return result == NSOrderedDescending;
            }];
            
            [responseObject setObject:array forKey:@"items"];
            dictTabData = responseObject;
            [[NSUserDefaults standardUserDefaults] setObject:responseObject forKey:@"tabData"];
        }
        
        //        RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
        //                                                            moduleName:@""
        //                                                     initialProperties:@{@"app_no":APP_NO,@"type":@"flashloan",@"openudid":[OpenUDID value],@"color":@"#328dfb",@"did":[EncryptAction getAuthDid],@"authkey":[EncryptAction getAuthKey],@"template":@"3",@"tabData":dictTabData?dictTabData:@""}
        //                                                         launchOptions:nil];
        //        rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
        //        delegate.rnController = [RootViewController new];
        //        delegate.rnController.view = rootView;
        
        GYNLog(@"JSView")
        [self getH5URL];
        
        [self performSelector:@selector(GotoAfterCheckVIew) withObject:nil afterDelay:1];
    }];
    
    
    
    
    
}


-(void)GotoAfterCheckVIew{
    //     [TalkingData trackEvent:@"进入审核之前" label:[APP_NO stringValue]];
    ChangeRootViewTool *choese = [ChangeRootViewTool getInstance];
    [choese gotoRootAfterCheckController];
}
- (void)goBeforCheckView{
    //    [TalkingData trackEvent:@"进入主程序页面" label:[APP_NO stringValue]];
    ChangeRootViewTool *choese = [ChangeRootViewTool getInstance];
    [choese GotoBefoteCheckController];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
